//
//  payPassWordViewController.m
//  dongfengTest
//
//  Created by wxt on 2021/3/16.
//

#import "PayPassWordViewController.h"
#import "CodeViewController.h"
#import "PGBView.h"
@interface PayPassWordViewController ()<UITextFieldDelegate,PGBViewDelegate>
@property(nonatomic,strong)PGBView * popView;
@property(nonatomic,strong)TKLtextFiled * payWordF;
@property(nonatomic,strong)TKLtextFiled * rePayWordF;
@property(nonatomic,strong)TKLlable * payWordMessageLab;
@property(nonatomic,strong)TKLlable * rePayWordMessageLab;
@property(nonatomic,strong)UIView * payLinView;
@property(nonatomic,strong)UIView * rePayLinView;
@property(nonatomic,strong)IMClientHttp *httpRequest;
@property (assign,nonatomic) NSInteger BiometryTypeNumber;
@property (strong,nonatomic) NSString * BiometryTypeStr;
@property(nonatomic,strong)UIButton * isHiddenBtn;
@property(nonatomic,strong)MBProgressHUD *hud;

@end

@implementation PayPassWordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    
    
    // Do any additional setup after loading the view.
    [self  loadUIView];
    
    [self faceID];
    
    // Do any additional setup after loading the view.
}



-(void)loadUIView{
    UIButton * backBtn =[UIButton createBtnFrame:CGRectMake(15, kStatusBarHeight+5, 18, 18) title:@"" bgImageName:@"fanhui" action:^(UIButton *button) {
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    [self.view addSubview:backBtn];
    
    TKLlable * lognLab = [TKLlable labelWithFrame:CGRectMake(30, 100, 50, 30) text:@"登录" textColor:JhColor(51, 51, 51) font:Font_6(24) textAlignment:Textleft backgroundColor:Ccolor];
    
    lognLab.font = [UIFont fontWithName:@"Arial-BoldMT" size:24];

    [self.view addSubview:lognLab];
    
    
    UIButton * messBtn = [UIButton createBtnFrame2:CGRectMake(30, CGRectGetMaxY(lognLab.frame)+30, 240, 16) title:@"为确保资金安全，请设置支付密码" bgImageName:@"" action:^(UIButton *button) {
        ;
    }];
    messBtn.titleLabel.textAlignment = Textleft;
    [self.view addSubview:messBtn];
    UIButton * signBtn = [UIButton createBtnFrame:CGRectMake(255, CGRectGetMaxY(lognLab.frame)+28, 20, 20) title:@"" bgImageName:@"tishi-3" action:^(UIButton *button) {
 
        self.popView.hidden = NO;

      
    }];
    [self.view addSubview:signBtn];
    self.popView = [PGBView alterViewWithtitle:@"支付密码用于验证登录和审批确认" withFrame:CGRectMake(255-115+10, CGRectGetMaxY(lognLab.frame)-12, 220, 40)];
    self.popView.delegate = self;
    [self.view addSubview:self.popView];
    self.popView.hidden = YES;
    
    
    self.payWordF = [TKLtextFiled FiledWithFrame:CGRectMake(30, CGRectGetMaxY(messBtn.frame)+30, kWidth-120, 20) text:@"请输入6位数支付密码" textColor:Bcolor font:Font_6(14) textAlignment:Textleft backgroundColor:Ccolor];
    self.payWordF.keyboardType = UIKeyboardTypeNumberPad;
    self.payWordF.secureTextEntry = YES;
    self.payWordF.delegate = self;
    [self.payWordF addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    
    [self.view addSubview:self.payWordF];
    
    self.payWordMessageLab = [TKLlable labelWithFrame:CGRectMake(30, CGRectGetMaxY(messBtn.frame)+15, kWidth-120, 18) text:@"" textColor:[UIColor redColor] font:Font_6(12) textAlignment:Textleft backgroundColor:Ccolor];
    [self.view addSubview:self.payWordMessageLab];
    
    
  
    
    self.isHiddenBtn = [UIButton createBtnFrame:CGRectMake(CGRectGetMaxX(self.payWordF.frame)+30, CGRectGetMaxY(messBtn.frame)+30, 30, 20) title:@"" bgImageName:@"yincang" action:^(UIButton *button) {
        [self.view endEditing:YES];
        [self ishiddenAction];
        
    }];

    self.isHiddenBtn.selected = NO;
    [self.isHiddenBtn setTitleColor:Bcolor forState:UIControlStateNormal];
    [self.view addSubview:self.isHiddenBtn];

    self.payLinView = [[UIView alloc]initWithFrame:CGRectMake(30, CGRectGetMaxY(self.payWordF.frame)+6, kWidth-60, 1)];
    self.payLinView.backgroundColor = JhColor(225, 225, 225);
    [self.view addSubview:self.payLinView];
    
    
    self.rePayWordF = [TKLtextFiled FiledWithFrame:CGRectMake(30, CGRectGetMaxY(self.payLinView.frame)+30, kWidth-120, 20) text:@"再次输入6位数支付密码" textColor:Bcolor font:Font_6(14) textAlignment:Textleft backgroundColor:Ccolor];
    [self.view addSubview:self.rePayWordF];
    self.rePayWordF.secureTextEntry = YES;
    self.rePayWordF.delegate = self;
    [self.rePayWordF addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.rePayWordF.keyboardType = UIKeyboardTypeNumberPad;
    self.rePayLinView = [[UIView alloc]initWithFrame:CGRectMake(30, CGRectGetMaxY(self.rePayWordF.frame)+6, kWidth-60, 1)];
    self.rePayLinView.backgroundColor = JhColor(225, 225, 225);
    
    [self.view addSubview:self.rePayLinView];
    
    //提示信息
    self.rePayWordMessageLab = [TKLlable labelWithFrame:CGRectMake(30, CGRectGetMaxY(self.payLinView.frame)+15, kWidth-60, 14) text:@"" textColor:[UIColor redColor] font:Font_6(12) textAlignment:Textleft backgroundColor:Ccolor];
    self.payWordMessageLab.hidden = YES;
    [self.view addSubview:self.rePayWordMessageLab];
    
    //next
    UIButton * nextBtn = [UIButton createBtnFrame:CGRectMake(30, CGRectGetMaxY(self.rePayLinView.frame)+30, kWidth-60, 44) title:@"确定" bgImageName:@"" action:^(UIButton *button) {
        [self.view endEditing:YES];
        self.payWordF.text = [self.payWordF.text stringByReplacingOccurrencesOfString:@" " withString:@""];
        self.rePayWordF.text=[self.rePayWordF.text stringByReplacingOccurrencesOfString:@" " withString:@""];
        
        if (self.payWordF.text.length == 6) {
            if (self.rePayWordF.text.length == 6) {
                if ([self.payWordF.text isEqualToString:self.rePayWordF.text]) {
                    
                    self.payWordMessageLab.hidden = YES;
                    self.rePayWordMessageLab.hidden = YES;
                    
                    
                    //获取用户信息，来决定走获取验证码还是重新获取
                    [self resGetCerCodeUrl];
                    
           

                }else{
                    self.rePayLinView.backgroundColor = JhColor(239, 45, 47);
                    self.rePayWordMessageLab.text = @"两次密码不一致";
                    self.rePayWordMessageLab.hidden = NO;
                    
                }
            }else{
                self.rePayLinView.backgroundColor = JhColor(239, 45, 47);
                self.rePayWordMessageLab.text = @"支付密码为6位数字";
                self.rePayWordMessageLab.hidden = NO;
            }
        }else{
            self.payLinView.backgroundColor = JhColor(239, 45, 47);
            self.payWordMessageLab.text = @"支付密码为6位数字";
            self.payWordMessageLab.hidden = NO;
        }
        

        
    }];
//    nextBtn
    nextBtn.backgroundColor = JhColor(21, 126, 251);
    nextBtn.layer.masksToBounds = YES;
    nextBtn.layer.cornerRadius = 5;
    [self.view addSubview:nextBtn];
    
    
    
}


-(void)textFieldDidBeginEditing:(UITextField *)textField{
  
    if (textField == self.payWordF) {
        self.payLinView.backgroundColor = JhColor(225, 225, 225);
        self.rePayLinView.backgroundColor = JhColor(225, 225, 225);
        self.payWordMessageLab.hidden = YES;
        self.rePayWordMessageLab.hidden = YES;
    }else{
        
        self.rePayLinView.backgroundColor = JhColor(225, 225, 225);
        self.payLinView.backgroundColor = JhColor(225, 225, 225);
        self.rePayWordMessageLab.hidden = YES;
        self.payWordMessageLab.hidden = YES;
    }
  
    
}
//监听长度
- (void)textFieldDidChange:(UITextField *)textField{
   
    if (textField == self.payWordF) {
        if (textField.text.length > 6) {
            self.payWordF.text = [textField.text substringToIndex:6];
        }
        if (textField.text.length == 0) {
            self.payWordMessageLab.hidden = YES;
            self.payLinView.backgroundColor = JhColor(225, 225, 225);
          
        }
    }else if(textField == self.rePayWordF){
        if (textField.text.length > 6) {
            self.rePayWordF.text = [textField.text substringToIndex:6];
        }
        if (textField.text.length == 0) {
            self.rePayLinView.backgroundColor = JhColor(225, 225, 225);
            self.rePayWordMessageLab.hidden = YES;
        }
    }

}

-(void)ishiddenAction{
    // 取反

    if (self.isHiddenBtn.selected == NO) {
        self.isHiddenBtn.selected = YES;
        [self.isHiddenBtn setBackgroundImage:[UIImage imageNamed:@"xianshi"] forState:UIControlStateNormal];
    }else{
        self.isHiddenBtn.selected = NO;
        [self.isHiddenBtn setBackgroundImage:[UIImage imageNamed:@"yincang"] forState:UIControlStateNormal];
    }
    
    self.payWordF.secureTextEntry = !self.payWordF.secureTextEntry;
    self.rePayWordF.secureTextEntry = !self.rePayWordF.secureTextEntry;
// 获得输入的值

    NSString *content = self.payWordF.text;
    NSString *recontent = self.rePayWordF.text;
 // 解决输入框从密文切换明文时出现空格的问题

    self.payWordF.text = @"";
    self.rePayWordF.text = @"";

    self.payWordF.text = content;
    self.rePayWordF.text = recontent;
 //如果是密文转明文进行二次编辑不会出现清空现象,如果是明文转密文进行二次编辑就会出现清空现象,进行判断,如果切换后此时输入框是密文状态,就保存原有内容并赋值给输入框,这样就不会出现清空现象了

   if (self.payWordF.secureTextEntry) {

 // 解决输入框从明文切换为密文时进行二次编辑出现清空现象

       [self.payWordF insertText:content];
       [self.rePayWordF insertText:recontent];

 }

 
    
    
}

-(void)faceID{
    
    self.BiometryTypeNumber = [BiomerTool isSupportBiometrics ];
   
    if (self.BiometryTypeNumber == 1) {
        self.BiometryTypeStr = @"指纹";
    }else if (self.BiometryTypeNumber == 2){
        self.BiometryTypeStr = @"面部";
    }else{
        self.BiometryTypeStr = @"生物";
    }
    
}



-(void)resGetCerCodeUrl{
    
    //获取用户uid
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
      self.hud.labelText = NSLocalizedString(@"请稍等", @"HUD loading title");
    [NetRequestClass NetRequestGETWithRequestURL:kUser_GetUserCerUID_Api WithParameter:@{@"uno":self.userName} WithReturnValeuBlock:^(id  _Nonnull returnValue) {
        NSLog(@"用户uid%@",returnValue);
        NSDictionary * dic = [TKLTools getDicFromResponse:returnValue];
        dic = [TKLTools deleNUllDic:dic];
        if ([dic[@"code"] intValue] ==200) {
            
            NSString * userUID =[TKLTools getValueFromDic:dic withKey:@"data"];
        
            if (userUID.length > 0) {
                //删除证书  重新获取授权码
                [self disUserCerUrlWithUid:userUID];
                
                
                //
               
            }else{
            //获取授权码
                [self getAuthorizationCodeUrl];
                
            }
            
            
        }else if([returnValue[@"code"] intValue] ==999){
//            self.hud.hidden = YES;
//            [MBProgressHUD showError:@"用户不存在" toView:self.view];
            [self getAuthorizationCodeUrl];
        }else{
            self.hud.hidden = YES;
            [MBProgressHUD showError:@"aaa" toView:self.view];
        }
        
        
        
        
        } WithErrorCodeBlock:^(id  _Nonnull errorCode) {
            ;
        } WithFailureBlock:^{
           
        }];
    
    
}
//作废证书
-(void)disUserCerUrlWithUid:(NSString *)userUid{
    [NetRequestClass TokenAuthNetRequestGETWithRequestURL:kUser_DiscardUserCer_Api WithParameter:@{@"uid":userUid} WithReturnValeuBlock:^(id  _Nonnull returnValue) {
        NSLog(@"作废证书%@",returnValue);
        
        
        IMUser * user = [IMUser userWithUserName:self.userName];
        if ([returnValue[@"code"] intValue ] ==200) {
          
            [user.cert deleteCert];
            //重新获取授权码
            [self getAuthorizationCodeUrlRefreshWithUid:userUid];


        }else{
            [user.cert deleteCert];
            [self getAuthorizationCodeUrlRefreshWithUid:userUid];

        }


        } WithErrorCodeBlock:^(id  _Nonnull errorCode) {

            [MBProgressHUD showError:@"调取接口失败" toView:self.view];
        } WithFailureBlock:^{
            ;
        }];
    
}
//重新获取授权码
-(void)getAuthorizationCodeUrlRefreshWithUid:(NSString *)uid{
    [NetRequestClass TokenAuthNetRequestGETWithRequestURL:kCertificate_RefreshCode_Api WithParameter:@{@"uid":uid} WithReturnValeuBlock:^(id  _Nonnull returnValue) {
      NSLog(@"重新获取%@",returnValue);

        NSDictionary *dic =  [TKLTools getDicFromResponse:returnValue];
        dic = [TKLTools deleNUllDic:dic];
      
        if ([returnValue[@"code"] intValue] == 200) {

            NSString * getCodeStr = dic [@"data"];
           
            if (getCodeStr.length > 0) {
                [IMUser signUpWithUserName:self.userName signCode:getCodeStr andCompleteBlock:^(int resultCode, IMUser *user) {

                    if (resultCode == IM_ER_SUCCESS) {
                         //注册成功下载证书
                        [self downCerAction];

                    }else{
                        self.hud.hidden = YES;
        //                NSLog(@"注册失败");
                        [MBProgressHUD showMessage:@"注册失败" toView:self.view];

                    }
                }];
            }else{
                self.hud.hidden = YES;
                [MBProgressHUD showError:@"授权码为空" toView:self.view];
            }
            
           
            
        
          
        }else{
            if ([returnValue[@"code"] intValue] == 999) {
                self.hud.hidden = YES;
                [MBProgressHUD showError:@"获取授权失败，请联系管理员" toView:self.view];
            }else{
                self.hud.hidden = YES;
                [MBProgressHUD showError:returnValue[@"msg"] toView:self.view];
            }
            
        }
        
        
       
        
        
        
        } WithErrorCodeBlock:^(id  _Nonnull errorCode) {
        
            
            
            
            [MBProgressHUD showError:@"调取接口失败" toView:self.view];
        } WithFailureBlock:^{
            [MBProgressHUD showError:@"调取接口失败" toView:self.view];
        }];
    
}
//获取授权码
-(void)getAuthorizationCodeUrl{
    

    [NetRequestClass TokenAuthNetRequestGETWithRequestURL:kCertificate_AuthCode_Api WithParameter:@{@"mobile":self.phoneNuM,@"checkCode":self.codeStr} WithReturnValeuBlock:^(id  _Nonnull returnValue) {
        NSLog(@"huoqu%@",returnValue);
        NSDictionary * dic = [TKLTools getDicFromResponse:returnValue];
        dic = [TKLTools deleNUllDic:dic];
        
        
    if ([dic[@"code"] intValue] == 200) {

      NSString * getCodeStr=  [TKLTools getValueFromDic:dic withKey:@"data"];
        
        
        if (getCodeStr.length > 0) {
            [IMUser signUpWithUserName:self.userName signCode:getCodeStr andCompleteBlock:^(int resultCode, IMUser *user) {

                if (resultCode == IM_ER_SUCCESS) {
                     //注册成功下载证书
                    
                    
                    [self downCerAction];
                    
      

                }else{
                    self.hud.hidden = YES;
                    NSLog(@"注册失败");
                    [MBProgressHUD showMessage:@"注册失败" toView:self.view];

                }
            }];

        }else{
            self.hud.hidden = YES;
            [MBProgressHUD  showError:@"授权码为空" toView:self.view];
        }
        
 

    }else{
        self.hud.hidden = YES;
        [MBProgressHUD  showError:@"用户不存在" toView:self.view];
    }



        } WithErrorCodeBlock:^(id  _Nonnull errorCode) {
            self.hud.hidden = YES;

        } WithFailureBlock:^{
            self.hud.hidden = YES;
        }];
    
    
}
//下载证书
-(void)downCerAction{
    IMUser * user = [IMUser userWithUserName:self.userName];
    [user.cert applyCertWithPIN:self.payWordF.text completeBlock:^(int resultCode) {
        self.hud.hidden = YES;
//                NSLog(@"%d",resultCode);
        if(resultCode == IM_ER_SUCCESS){
  
    //存储密码，签名使用
            [self  inisterCerList ];
            
            if ([self.pushPath containsString:@"Forget"]) {
                self.hud.hidden = YES;
                [MBProgressHUD showError:@"证书下载成功" toView:self.view];
                [self performSelector:@selector(delayMethod) withObject:nil/*可传任意类型参数*/ afterDelay:2.0];
            } else{

                self.hud.hidden = YES;
                [MBProgressHUD showError:@"证书下载成功，请重新登录" toView:self.view];
                [self performSelector:@selector(delayMethodAction) withObject:nil/*可传任意类型参数*/ afterDelay:2.0];
                
          
                   
            }
 

        }else{
            self.hud.hidden = YES;
            [MBProgressHUD showMessage:@"下载证书失败" toView:self.view];
            NSLog(@"下载证书失败,%@",[IMError getMsgWithErr:resultCode]);
        }
    }];
    
    
}
-(void)delayMethod{

    CodeViewController * codeVC = [[CodeViewController alloc]init];
    codeVC.userName  = self.userName;
    codeVC.pushPath = @"newForget";
    codeVC.phoneNumberStr = self.phoneNuM;
    codeVC.modalPresentationStyle = 0;
    [self presentViewController:codeVC animated:YES completion:nil];

 
}
-(void)delayMethodAction{

    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"downCerSuccess" object:@""];
    
    //返回到根视图
    UIViewController *rootVC = self.presentingViewController;
    while(rootVC.presentingViewController) {
    rootVC= rootVC.presentingViewController;
    }
    
 [rootVC dismissViewControllerAnimated:YES completion:nil];

 
}
- (void)dealloc {
    
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}
-(void)textViewCancel{
    
    self.popView.hidden = YES;
    
    
}
-(void)inisterCerList{
  
    FMDatabase *database =  [DataBaseTool openDataBase];
    
    NSString *selectSql = [NSString stringWithFormat:@"select * from userCer where userName = '%@'",self.userName];
    
    FMResultSet *resultSet = [database executeQuery:selectSql];
   
    
    if ( [resultSet next]) {
    
          BOOL update=[database executeUpdate:@"update userCer set payWord = ? where userName =?",self.payWordF.text,self.userName];
          if (update) {
              NSLog(@"修改成功");
          } else {
              NSLog(@"修改失败");
          }
        
        
        
    }else{
        NSString *insertSql = [NSString stringWithFormat:@"INSERT INTO 'userCer' ('userName', 'payWord') VALUES ('%@', '%@')",self.userName,self.payWordF.text];
               BOOL result = [database executeUpdate:insertSql];
      if (!result) {
          NSLog(@"插入失败");
      }else{
          NSLog(@"插入成功");
      }
        
    }
    
    [database close];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
